package com.globaldom.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.CivResource;
import com.globaldom.model.MilResource;
import com.globaldom.utils.Constants;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/addmilitary")
public class MilitaryAddController {
	public MilitaryAddController() {
	}
	private static final Logger log = Logger.getLogger(MilitaryAddController.class.getName());

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> addMil(@RequestParam int milType, @RequestParam long milNum, HttpSession session,
			HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}

		PersistenceManager pm = PMF.get().getPersistenceManager();
		PersistenceManager pmciv = PMF.get().getPersistenceManager();
		try {
			MilResource mil = pm.getObjectById(MilResource.class, personID +"/" + milType);
			long num = milNum - mil.getMilAvailable();
			if (num < 1) {
				map.put(Constants.STATUS, "-ER");
				map.put(Constants.CODE, "304");
				return map;
			}

			Query	query = pmciv.newQuery(CivResource.class, "person==pid");
			query.declareParameters("String pid");
			List<CivResource> civList = (List<CivResource>) query.execute(personID);

			for (CivResource civResource : civList) {
				// EntityManager emciv = EMF.get().createEntityManager();
				if (civResource.getResType() > CivResource.GOLD)
					continue;
				int cost = ((9 - civResource.getResType()) * 10) * (milType + 1);
				long newvalue = civResource.getResAvailable() - (cost * num);
				if (newvalue < 0) {
					map.put(Constants.STATUS, "-ER");
					map.put(Constants.CODE, "404");
					return map;
				}
				civResource.setResAvailable(newvalue);

			}
			pmciv.makePersistentAll(civList);
			pm.makePersistent(mil);
			mil.setMilAvailable(milNum);

			map.put(Constants.STATUS, "+OK");
			map.put(Constants.CODE, "" + mil.getMilAvailable());
		} catch (Exception ex) {
			log.severe("Exception while adding military " + ex.getLocalizedMessage() + " /" + ex);
		} finally {

			pm.close();
			pmciv.close();

		}
		return map;
	}

}
